<?php
use think\Db;
use Aliyun\Core\Config;  
use Aliyun\Core\Profile\DefaultProfile;  
use Aliyun\Core\DefaultAcsClient;  
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
/**
 * @param string $url post请求地址
 * @param array $params
 * @return mixed
 */
function httpPost($url, array $params = array())
{
    $data_string = json_encode($params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt(
        $ch, CURLOPT_HTTPHEADER,
        array(
            'Content-Type: application/json'
        )
    );
    $data = curl_exec($ch);
    curl_close($ch);
    return ($data);
}

/**
 * @param string $url get请求地址
 * @param int $httpCode 返回状态码
 * @return mixed
 */
function httpGet($url, &$httpCode = 0)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //不做证书校验,部署在linux环境下请改为true
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $file_contents;
}
/**
 * 字符串截取，支持中文和其他编码
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
	if (function_exists("mb_substr"))
		$slice = mb_substr($str, $start, $length, $charset);
	elseif (function_exists('iconv_substr')) {
		$slice = iconv_substr($str, $start, $length, $charset);
		if (false === $slice) {
			$slice = '';
		}
	} else {
		$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("", array_slice($match[0], $start, $length));
	}
	return $suffix ? $slice . '...' : $slice;
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

/**
 * 读取配置
 * @return array 
 */
function load_config(){
    $list = Db::name('config')->select();
    $config = [];
    foreach ($list as $k => $v) {
        $config[trim($v['name'])]=$v['value'];
    }

    return $config;
}


/**
* 验证手机号是否正确
* @author honfei
* @param number $mobile
*/
function isMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain .'/uploads/images/'. $url;
        }
        return $url;
    }
}


/** 
 * 阿里云云通信发送短息 
 * @param string $mobile    接收手机号 
 * @param string $tplCode   短信模板ID
 * @param array  $tplParam  短信内容
 * @return array 
 */  
function sendMsg($mobile,$tplCode,$tplParam){  
    if( empty($mobile) || empty($tplCode) ) return array('Message'=>'缺少参数','Code'=>'Error');  
    if(!isMobile($mobile)) return array('Message'=>'无效的手机号','Code'=>'Error');  
      
    require_once '../extend/aliyunsms/vendor/autoload.php';  
    Config::load();             //加载区域结点配置   
    $accessKeyId = config('alisms_appkey');  
    $accessKeySecret = config('alisms_appsecret');  
    if( empty($accessKeyId) || empty($accessKeySecret) ) return array('Message'=>'请先在后台配置appkey和appsecret','Code'=>'Error'); 
    $templateParam = $tplParam; //模板变量替换  
    //$signName = (empty(config('alisms_signname'))?'阿里大于测试专用':config('alisms_signname'));  
	$signName = config('alisms_signname');  
    //短信模板ID 
    $templateCode = $tplCode;   
    //短信API产品名（短信产品名固定，无需修改）  
    $product = "Dysmsapi";  
    //短信API产品域名（接口地址固定，无需修改）  
    $domain = "dysmsapi.aliyuncs.com";  
    //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）  
    $region = "cn-hangzhou";     
    // 初始化用户Profile实例  
    $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);  
    // 增加服务结点  
    DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);  
    // 初始化AcsClient用于发起请求  
    $acsClient= new DefaultAcsClient($profile);  
    // 初始化SendSmsRequest实例用于设置发送短信的参数  
    $request = new SendSmsRequest();  
    // 必填，设置雉短信接收号码  
    $request->setPhoneNumbers($mobile);  
    // 必填，设置签名名称  
    $request->setSignName($signName);  
    // 必填，设置模板CODE  
    $request->setTemplateCode($templateCode);  
    // 可选，设置模板参数     
    if($templateParam) {
        $request->setTemplateParam(json_encode($templateParam));
    }
    //发起访问请求  
    $acsResponse = $acsClient->getAcsResponse($request);   
    //返回请求结果  
    $result = json_decode(json_encode($acsResponse),true); 

    return $result;  
}  



//生成网址的二维码 返回图片地址
function Qrcode($token, $url, $size = 8){
    vendor('phpqrcode.phpqrcode');
    $md5 = md5($token);
    $dir = date('Ymd'). '/' . substr($md5, 0, 10) . '/';
    $patch = 'qrcode/' . $dir;
    if (!file_exists($patch)){
        mkdir($patch, 0755, true);
    }
    $file = 'qrcode/' . $dir . $md5 . '.png';
    $fileName =  $file;
    if (!file_exists($fileName)) {

        $level = 'L';
        $data = $url;
        \QRcode::png($data, $fileName, $level, $size, 2, true);
    }
    return $file;
}



/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name) {
    $result = false;
    if(is_dir($dir_name)){
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}



//时间格式化1
function formatTime($time) {
    $now_time = time();
    $t = $now_time - $time;
    $mon = (int) ($t / (86400 * 30));
    if ($mon >= 1) {
        return '一个月前';
    }
    $day = (int) ($t / 86400);
    if ($day >= 1) {
        return $day . '天前';
    }
    $h = (int) ($t / 3600);
    if ($h >= 1) {
        return $h . '小时前';
    }
    $min = (int) ($t / 60);
    if ($min >= 1) {
        return $min . '分钟前';
    }
    return '刚刚';
}


//时间格式化2
function pincheTime($time) {
     $today  =  strtotime(date('Y-m-d')); //今天零点
      $here   =  (int)(($time - $today)/86400) ; 
      if($here==1){
          return '明天';  
      }
      if($here==2) {
          return '后天';  
      }
      if($here>=3 && $here<7){
          return $here.'天后';  
      }
      if($here>=7 && $here<30){
          return '一周后';  
      }
      if($here>=30 && $here<365){
          return '一个月后';  
      }
      if($here>=365){
          $r = (int)($here/365).'年后'; 
          return   $r;
      }
     return '今天';
}


function getRandomString($len, $chars=null){
    if (is_null($chars)){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }  
    mt_srand(10000000*(double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
        $str .= $chars[mt_rand(0, $lc)];  
    }
    return $str;
}


function random_str($length){
    //生成一个包含 大写英文字母, 小写英文字母, 数字 的数组
    $arr = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
 
    $str = '';
    $arr_len = count($arr);
    for ($i = 0; $i < $length; $i++)
    {
        $rand = mt_rand(0, $arr_len-1);
        $str.=$arr[$rand];
    }
 
    return $str;
}
/**
 * 计算两点地理坐标之间的距离
 * @param Decimal $longitude1 起点经度
 * @param Decimal $latitude1 起点纬度
 * @param Decimal $longitude2 终点经度
 * @param Decimal $latitude2 终点纬度
 * @param Int   $unit    单位 1:米 2:公里
 * @param Int   $decimal  精度 保留小数位数
 * @return Decimal
 */
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){

    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;

    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;

    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI /180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if($unit==2){
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);

}

/**
 * 获取星座信息
 * @param $month
 * @param $day
 * @return bool
 */
function constellation($month, $day) {
    // 检查参数有效性
    if ($month < 1 || $month > 12 || $day < 1 || $day > 31) return false;
    // 星座名称以及开始日期
    if(($month == 1 && $day >= 20) || ($month == 2 && $day <= 18)) {
        $xingzuo = "水瓶座";
    }else if(($month == 2 && $day >= 19) || ($month == 3 && $day <= 20)) {
        $xingzuo = "双鱼座";
    }else if (($month == 3 && $day >= 21) || ($month == 4 && $day <= 19)) {
        $xingzuo = "白羊座";
    }else if (($month == 4 && $day >= 20) || ($month == 5 && $day <= 20)) {
        $xingzuo = "金牛座";
    }else if (($month == 5 && $day >= 21) || ($month == 6 && $day <= 21)) {
        $xingzuo = "双子座";
    }else if (($month == 6 && $day >= 22) || ($month == 7 && $day <= 22)) {
        $xingzuo = "巨蟹座";
    }else if (($month == 7 && $day >= 23) || ($month == 8 && $day <= 22)) {
        $xingzuo = "狮子座";
    }else if (($month == 8 && $day >= 23) || ($month == 9 && $day <= 22)) {
        $xingzuo = "处女座";
    }else if (($month == 9 && $day >= 23) || ($month == 10 && $day <= 23)) {
        $xingzuo = "天秤座";
    }else if (($month == 10 && $day >= 24) || ($month == 11 && $day <= 22)) {
        $xingzuo = "天蝎座";
    }else if (($month == 11 && $day >= 23) || ($month == 12 && $day <= 21)) {
        $xingzuo = "射手座";
    }else if (($month == 12 && $day >= 22) || ($month == 1 && $day <= 19)) {
        $xingzuo = "摩羯座";
    }

    return $xingzuo;
}

/**
 * 获取系统推荐
 */
function getSystemPair($userInfo=[],$config=[]){
    $list = cache('SystemPairList');
    if(!$list){
        $heartInfo= Db('heart')->where('user_id',$userInfo['id'])->whereTime('update_time','<',date('Y-m-d',time()))->column('to_user_id');  //今天心动
        if($heartInfo){
            $where['a.id'] = ['not in',$heartInfo];  //心动过的不展示
        }
        $where['status'] = 1;
        $where['height'] = ['between',[$userInfo['min_height'],$userInfo['max_height']]];  //身高
        $where['age'] = ['between',[$userInfo['min_age'],$userInfo['max_age']]];   //年龄
        $where['offer_id'] = ['gt',$userInfo['other_offer_id']];   //学历
        $where['sex'] = ['neq',$userInfo['sex']];   //性别
        $list = Db('member')
            ->alias('a')
            ->join('think_area b','a.home_province=b.id')
            ->join('think_area c','a.home_city=c.id')
            ->where($where)
            ->order('a.id desc')
            ->limit($config['view_total'])
            ->field('a.lat,a.lng,address,habit,a.id,head_img,b.name as home_province,c.name as home_city,wx_code,star')
            ->select();
        if($list){
            foreach ($list as $k => $v){
                if($userInfo['habit'] && $v['habit']){
                    $com = array_intersect(explode($userInfo['habit']),explode(',',$v['habit']));
                    if(!$com){
                        unset($list[$k]);
                    }
                }
            }
            foreach ($list as &$v){
                if(!strpos($v['head_img'],'ttp')){
                    $v['head_img'] = 'http://' . $_SERVER['SERVER_NAME'] . '/uploads/face/' . $v['head_img'];
                }
            }
            if(count($list) < $config['view_total']){
                cache('SystemPairList','');   //数量不够
            }else{
                cache('SystemPairList',$list);
            }

        }
    }
    return $list;
}
/**
 * 获取推荐列表
 */
function getPairList($page=1,$userInfo=[]){
    $per_page_num = 2;

    $heartInfo= Db('heart')->where('user_id',$userInfo['id'])->whereTime('update_time','<',date('Y-m-d',time()))->column('to_user_id');  //今天心动
    if($heartInfo){
        $where['a.id'] = ['not in',$heartInfo];  //心动过的不展示
    }
    $where['height'] = ['between',[$userInfo['min_height'],$userInfo['max_height']]];  //身高
    $where['age'] = ['between',[$userInfo['min_age'],$userInfo['max_age']]];   //年龄
    $where['offer_id'] = ['gt',$userInfo['other_offer_id']];   //学历
    $where['sex'] = ['neq',$userInfo['sex']];   //性别
    $otherInfo = Db('member')
        ->alias('a')
        ->join('think_area b','a.home_province=b.id')
        ->join('think_area c','a.home_city=c.id')
        ->where($where)
        ->order('a.id desc')
        ->field('a.id,head_img,b.name as home_province,c.name as home_city,wx_code,star')
        ->paginate($per_page_num,1,['page'=>$page])
        ->toArray();

    if(!$otherInfo){
        return json(['code'=>0,'msg'=>'暂无推荐信息']);
    }
    foreach ($otherInfo['data'] as &$v){
        $v['head_img'] = 'http://' . $_SERVER['SERVER_NAME'].'/uploads/face/'.$v['head_img'];
    }
    return $otherInfo;
}
/**
 * 查看未读留言数
 * @param int $me  默认1=>我给别人的留言未读数,2=>别人给我的留言未读数
 */
function getNoteNoReadNum($user_id=0,$me=1){
    if(!$user_id){
        return 0;
    }
    $where['is_read'] = 0;
    if($me == 1){
        $where['user_id'] = $user_id;
    }else{
        $where['to_user_id'] = $user_id;
    }
    $num = Db('note')->where($where)->group('room_id')->count(1)?:0;
    return $num;
}